import 'package:flutter/material.dart';
import 'package:sample2/helper/app_helper.dart';
import 'package:sample2/model/chat/chat_channel.dart';
import 'package:sample2/model/user_info.dart';
import 'package:sample2/pages/chat/channel/chat_add_channel.dart';
import 'package:sample2/pages/chat/channel/chat_channel_item.dart';
import 'package:sample2/services/chat_service.dart';

class ChatChannelPage extends StatefulWidget {
  const ChatChannelPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return ChatChannelPageState();
  }
}

class ChatChannelPageState extends State {
  late List<ChatChannel>? _channels = [];
  @override
  void initState() {
    
    _getChannel();

    super.initState();
  }

  void _getChannel() {
    ChatService.getChannels()?.then((List<ChatChannel> channels) {
      if(mounted){
        setState(() {
          _channels = channels;
        });
      }
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Channels"),
        actions: [
          IconButton(
              onPressed: () {
                AppHelper.shared.getUserInfo().then((UserInfo? userInfo) {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (BuildContext context) {
                    return AddChatChannel(adminId: userInfo?.userid ?? "",onSuccessCreateChannel: () {
                      //refresh list data
                      _getChannel();
                    },);
                  }));
                });
              },
              icon: const Icon(Icons.add))
        ],
      ),
      body: ListView.separated(
          itemBuilder: (BuildContext context, int index) {
            return ChatChannelItem(
              channelItem: _channels![index],
            );
          },
          separatorBuilder: (BuildContext context, int index) {
            return const Divider(
              color: Colors.black,
              height: 1,
            );
          },
          itemCount: _channels?.length ?? 0),
    );
  }
}
